package com.recsmile.rpc.provider.net;

import com.recsmile.rpc.provider.RpcServerLoader;
import com.recsmile.rpc.provider.net.codec.MessageSendHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.net.InetSocketAddress;

/**
 * Created by Administrator on 2016/8/7.
 */
public class RpcMessageSenderInitTask implements Runnable{
    private InetSocketAddress serverAddress;
    private EventLoopGroup eventLoopGroup;
    private RpcServerLoader rpcServerLoader;

    public RpcMessageSenderInitTask(InetSocketAddress serverAddress, EventLoopGroup eventLoopGroup, RpcServerLoader rpcServerLoader) {
        this.serverAddress = serverAddress;
        this.eventLoopGroup = eventLoopGroup;
        this.rpcServerLoader = rpcServerLoader;
    }

    public void run() {
        Bootstrap bootstrap = new Bootstrap();
        try {
            bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class).handler(new MessageSendChannelInitializer()).option(ChannelOption.SO_KEEPALIVE, true);
            bootstrap.connect(serverAddress).sync().addListener(new ChannelFutureListener() {
                public void operationComplete(ChannelFuture future) throws Exception {
                    rpcServerLoader.setMessageSendHandler(future.channel().pipeline().get(MessageSendHandler.class));
                }
            });
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
